package com.zzedu.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.system.service.ISysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Controller;

import java.util.Map;

@Controller
public class WebSocketController {
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    SimpUserRegistry simpUserRegistry;
//    @MessageMapping("/welcome")
//    @SendTo("/topic/getResponse") // 服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
//    public AjaxResult say(Map map) throws Exception {
//        return AjaxResult.success(map);
//    }
    @MessageMapping("/welcome")
//    @SendToUser("/notifications/msg")
    public AjaxResult notifications(Map map) throws Exception {
        String msg="欢迎使用"+sysConfigService.selectConfigByKey("sys.title.text")+"系统";
        if(CollectionUtils.isNotEmpty(simpUserRegistry.getUsers())){
            for(SimpUser simpUser:simpUserRegistry.getUsers()){
                simpMessagingTemplate.convertAndSendToUser(simpUser.getName(),"/notifications/msg", JSON.toJSONString(AjaxResult.success(msg)));
            }
        }
        return AjaxResult.success(msg);
    }
//    @PostConstruct
//    public void pushToAllCLient() {
//        CompletableFuture.runAsync(() -> {
//            while (true) {
//                try {
//                    TimeUnit.SECONDS.sleep(10L);
//                    simpMessagingTemplate.convertAndSend("/topic/getResponse", AjaxResult.success("欢迎体验bootdo,这是一个任务计划，使用了websocket和quzrtz技术，可以在计划列表中取消，欢迎您加入qq群交流学习!"));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }
}
